<template>
  <div>
    <h1 class="page-title">RFID扫描</h1>

    <a-row :gutter="24">
      <a-col :xs="24" :lg="12">
        <a-card class="scan-card">
          <template #title>
            <div class="card-title">
              <scan-outlined style="font-size: 20px; color: #1890ff" />
              <span>RFID扫描器</span>
              <a-button
                type="link"
                size="small"
                @click="toggleDebugInfo"
                style="margin-left: auto"
              >
                {{ showDebugInfo ? "隐藏调试" : "显示调试" }}
              </a-button>
            </div>
          </template>

          <div class="scanner-container">
            <div class="scanner-animation" :class="{ scanning: isScanning }">
              <div class="scanner-light"></div>
            </div>

            <div class="scanner-status">
              <a-badge :status="deviceStatus" :text="deviceStatusText" />
              <p>{{ statusMessage }}</p>
              <a-tag
                :color="
                  connectionStatus === 'connected'
                    ? 'green'
                    : connectionStatus === 'connecting'
                    ? 'blue'
                    : 'red'
                "
              >
                {{ mqttStatusText }}
              </a-tag>
              <div v-if="lastError" class="error-message">
                <a-alert type="error" :message="lastError" banner />
              </div>

              <div class="connection-options">
                <a-button
                  type="primary"
                  @click="reconnectMqtt"
                  :disabled="connectionStatus === 'connecting'"
                >
                  重新连接MQTT
                </a-button>
              </div>
            </div>

            <div v-if="showDebugInfo" class="debug-info">
              <a-divider>调试信息</a-divider>
              <a-list
                size="small"
                bordered
                :dataSource="debugInfo"
                style="max-height: 200px; overflow-y: auto; text-align: left"
              >
                <template #renderItem="{ item }">
                  <a-list-item>{{ item }}</a-list-item>
                </template>
              </a-list>
            </div>

            <div class="scanner-controls">
              <a-form layout="vertical">
                <a-form-item label="RFID ID">
                  <a-input
                    v-model:value="rfidId"
                    placeholder="16位RFID标识符"
                    :disabled="isScanning"
                    :maxLength="16"
                  />
                  <div class="helper-text">
                    输入模拟的RFID ID或点击下方按钮生成随机ID
                  </div>
                </a-form-item>

                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-button
                      type="default"
                      block
                      @click="generateRandomRfid"
                      :disabled="isScanning"
                    >
                      <template #icon><reload-outlined /></template>
                      生成随机ID
                    </a-button>
                  </a-col>
                  <a-col :span="12">
                    <a-button
                      type="primary"
                      block
                      @click="startScan"
                      :loading="isScanning"
                      :disabled="
                        !rfidId ||
                        rfidId.length !== 16 ||
                        connectionStatus !== 'connected'
                      "
                    >
                      <template #icon><scan-outlined /></template>
                      模拟扫描
                    </a-button>
                  </a-col>
                </a-row>
              </a-form>
            </div>
          </div>
        </a-card>

        <a-card title="扫描结果历史" class="mt-16">
          <a-empty v-if="scanHistory.length === 0" description="暂无扫描记录" />

          <a-list v-else>
            <a-list-item v-for="(item, index) in scanHistory" :key="index">
              <a-list-item-meta>
                <template #title>
                  <div class="scan-history-item">
                    <span>{{ item.rfid_id }}</span>
                    <span>{{ item.time }}</span>
                  </div>
                </template>
                <template #description>
                  <div class="scan-result-tags">
                    <a-tag color="blue" v-if="item.medicine">{{
                      item.medicine.name
                    }}</a-tag>
                    <a-tag color="green" v-if="item.success">扫描成功</a-tag>
                    <a-tag color="red" v-else>扫描失败</a-tag>
                  </div>
                </template>
              </a-list-item-meta>

              <template #actions>
                <a-button
                  type="link"
                  @click="viewDetail(item)"
                  v-if="item.medicine"
                >
                  详情
                </a-button>
                <a-button type="link" @click="repeatScan(item)">
                  重新扫描
                </a-button>
              </template>
            </a-list-item>
          </a-list>
        </a-card>
      </a-col>

      <a-col :xs="24" :lg="12">
        <a-card v-if="currentResult" class="result-card">
          <template #title>
            <div class="card-title">
              <inbox-outlined style="font-size: 20px; color: #1890ff" />
              <span>扫描结果</span>
            </div>
          </template>

          <div v-if="currentResult.success" class="scan-result-success">
            <a-result
              status="success"
              title="扫描成功"
              :sub-title="`RFID ID: ${currentResult.rfid_id}`"
            >
              <template #extra>
                <div class="result-actions">
                  <a-button type="primary" @click="viewTrace">
                    <template #icon><apartment-outlined /></template>
                    查看追溯
                  </a-button>
                  <a-button @click="verifyMedicine">
                    <template #icon><safety-certificate-outlined /></template>
                    验证真伪
                  </a-button>
                </div>
              </template>
            </a-result>

            <a-divider />

            <div class="medicine-info">
              <h3>药品信息</h3>
              <a-descriptions bordered :column="1">
                <a-descriptions-item label="药品名称">
                  {{ currentResult.medicine.name }}
                </a-descriptions-item>
                <a-descriptions-item label="规格">
                  {{ currentResult.medicine.spec }}
                </a-descriptions-item>
                <a-descriptions-item label="生产厂家">
                  {{ currentResult.medicine.manufacturer }}
                </a-descriptions-item>
                <a-descriptions-item label="生产批次">
                  <a-tag color="blue">{{ currentResult.medicine.batch }}</a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="生产日期">
                  {{ formatDate(currentResult.medicine.production_date) }}
                </a-descriptions-item>
                <a-descriptions-item label="有效期至">
                  {{ formatDate(currentResult.medicine.expiry_date) }}
                  <a-tag
                    v-if="isExpired(currentResult.medicine.expiry_date)"
                    color="red"
                    >已过期</a-tag
                  >
                  <a-tag v-else color="green">有效期内</a-tag>
                </a-descriptions-item>
              </a-descriptions>
            </div>
          </div>

          <div v-else class="scan-result-error">
            <a-result
              status="error"
              title="扫描失败"
              :sub-title="`RFID ID: ${currentResult.rfid_id}`"
            >
              <template #extra>
                <div class="result-actions">
                  <a-button @click="startScan">
                    <template #icon><reload-outlined /></template>
                    重新扫描
                  </a-button>
                  <a-button type="primary" @click="addNewMedicine">
                    <template #icon><plus-outlined /></template>
                    添加新药品
                  </a-button>
                </div>
              </template>
            </a-result>

            <a-divider />

            <a-alert
              type="warning"
              message="未找到药品信息"
              description="系统中不存在该RFID对应的药品信息。可能是该药品未录入系统，或者RFID ID有误。"
              show-icon
            />
          </div>
        </a-card>

        <a-card v-else class="help-card">
          <template #title>
            <div class="card-title">
              <info-circle-outlined style="font-size: 20px; color: #1890ff" />
              <span>RFID扫描器使用说明</span>
            </div>
          </template>

          <div class="help-content">
            <a-steps direction="vertical" :current="-1">
              <a-step
                title="准备扫描"
                description="确保RFID扫描器已连接并准备工作，设备状态指示灯显示绿色表示正常."
              />
              <a-step
                title="放置药品"
                description="将药品放置在扫描区域内，确保RFID标签朝向扫描器."
              />
              <a-step
                title="开始扫描"
                description="点击'扫描'按钮开始扫描，或者触发扫描器的物理按钮."
              />
              <a-step
                title="查看结果"
                description="扫描完成后，系统会显示扫描结果。如果成功，可以查看药品详情或追溯信息."
              />
            </a-steps>

            <a-divider />

            <a-alert
              type="info"
              message="RFID扫描模拟器"
              description="本页面提供RFID扫描器的模拟功能，方便测试和演示系统。在实际环境中，系统会连接物理RFID扫描设备进行操作。"
              show-icon
            />
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import moment from "moment";
import api from "@/services/api";
import {
  connectMqtt,
  disconnectMqtt,
  connectionStatus,
  lastError,
  simulateMqttMessage,
  debugInfo,
} from "@/services/mqtt";
import {
  ScanOutlined,
  ReloadOutlined,
  InboxOutlined,
  InfoCircleOutlined,
  ApartmentOutlined,
  SafetyCertificateOutlined,
  PlusOutlined,
} from "@ant-design/icons-vue";

// Types
interface ScanResult {
  rfid_id: string;
  time: string;
  success: boolean;
  medicine?: any;
}

// State
const router = useRouter();
const rfidId = ref("");
const isScanning = ref(false);
const statusMessage = ref("正在连接MQTT服务...");
const deviceStatus = ref<"success" | "processing" | "error">("processing");
const deviceStatusText = ref("连接中");
const scanHistory = ref<ScanResult[]>([]);
const currentResult = ref<ScanResult | null>(null);

// 添加调试模式开关
const showDebugInfo = ref(false);
const toggleDebugInfo = () => {
  showDebugInfo.value = !showDebugInfo.value;
};

// 监听MQTT连接状态
const mqttStatusText = computed(() => {
  switch (connectionStatus.value) {
    case "connected":
      return "MQTT已连接";
    case "connecting":
      return "MQTT连接中...";
    case "disconnected":
      return "MQTT未连接";
  }
});

// 更新设备状态
const updateDeviceStatus = () => {
  switch (connectionStatus.value) {
    case "connected":
      deviceStatus.value = "success";
      deviceStatusText.value = "在线";
      statusMessage.value = "MQTT已连接，等待RFID扫描...";
      break;
    case "connecting":
      deviceStatus.value = "processing";
      deviceStatusText.value = "连接中";
      statusMessage.value = "正在连接MQTT服务...";
      break;
    case "disconnected":
      deviceStatus.value = "error";
      deviceStatusText.value = "离线";
      statusMessage.value = `MQTT连接断开${
        lastError.value ? ": " + lastError.value : ""
      }`;
      break;
  }
};

// Methods
const generateRandomRfid = () => {
  // Generate a random 16-digit number for RFID
  const randomRfid = Math.floor(
    1000000000000000 + Math.random() * 9000000000000000
  ).toString();
  rfidId.value = randomRfid;
};

// 重新连接MQTT
const reconnectMqtt = () => {
  message.info("正在重新连接MQTT...");
  connectMqtt(handleRfidReceived);
};

// 处理接收到的RFID ID
const handleRfidReceived = async (receivedRfidId: string) => {
  console.log("接收到RFID ID:", receivedRfidId);
  rfidId.value = receivedRfidId;

  // 显示扫描中状态
  isScanning.value = true;
  statusMessage.value = "正在处理RFID数据...";

  try {
    // 查询药品信息
    const response = await api.queryMedicine(receivedRfidId);

    // 创建扫描结果
    const result: ScanResult = {
      rfid_id: receivedRfidId,
      time: moment().format("YYYY-MM-DD HH:mm:ss"),
      success: true,
      medicine: response.data,
    };

    currentResult.value = result;
    scanHistory.value.unshift(result);

    // 只保留最近10条记录
    if (scanHistory.value.length > 10) {
      scanHistory.value = scanHistory.value.slice(0, 10);
    }

    // 保存到localStorage
    saveScanHistory();

    message.success("RFID扫描成功");
    statusMessage.value = "扫描成功，可以查看药品信息";
  } catch (error) {
    console.error("查询RFID信息失败:", error);

    // 创建错误结果
    const result: ScanResult = {
      rfid_id: receivedRfidId,
      time: moment().format("YYYY-MM-DD HH:mm:ss"),
      success: false,
    };

    currentResult.value = result;
    scanHistory.value.unshift(result);

    // 只保留最近10条记录
    if (scanHistory.value.length > 10) {
      scanHistory.value = scanHistory.value.slice(0, 10);
    }

    // 保存到localStorage
    saveScanHistory();

    message.error("未找到该RFID对应的药品信息");
    statusMessage.value = "扫描完成，但未找到药品信息";
  } finally {
    isScanning.value = false;
  }
};

// 模拟扫描（通过MQTT发送模拟消息）
const startScan = async () => {
  if (!rfidId.value || rfidId.value.length !== 16) {
    message.warning("请输入16位RFID标识符");
    return;
  }

  isScanning.value = true;
  statusMessage.value = "正在模拟RFID扫描...";

  try {
    // 模拟发送MQTT消息
    const success = simulateMqttMessage(rfidId.value);

    if (!success) {
      message.error("MQTT未连接，无法模拟扫描");
      statusMessage.value = "MQTT未连接，请检查连接状态";
    }

    // 不在这里处理扫描结果，由MQTT消息监听器处理
  } catch (error) {
    console.error("模拟扫描失败:", error);
    message.error("模拟扫描失败");
  } finally {
    // 短暂延迟后恢复状态
    setTimeout(() => {
      isScanning.value = false;
    }, 1000);
  }
};

const viewDetail = (item: ScanResult) => {
  currentResult.value = item;
};

const repeatScan = (item: ScanResult) => {
  rfidId.value = item.rfid_id;
  startScan();
};

const viewTrace = () => {
  if (currentResult.value && currentResult.value.success) {
    router.push({
      path: "/trace",
      query: { rfid: currentResult.value.rfid_id },
    });
  }
};

const verifyMedicine = () => {
  if (currentResult.value && currentResult.value.success) {
    router.push({
      path: "/verification",
      query: { rfid: currentResult.value.rfid_id },
    });
  }
};

const addNewMedicine = () => {
  router.push("/medicine-management");
};

const formatDate = (dateStr: string): string => {
  return moment(dateStr, "YYYYMMDD").format("YYYY-MM-DD");
};

const isExpired = (dateStr: string): boolean => {
  return moment(dateStr, "YYYYMMDD").isBefore(moment(), "day");
};

const saveScanHistory = () => {
  localStorage.setItem("scanHistory", JSON.stringify(scanHistory.value));
};

const loadScanHistory = () => {
  const history = localStorage.getItem("scanHistory");
  if (history) {
    try {
      scanHistory.value = JSON.parse(history);
    } catch (e) {
      console.error("Failed to parse scan history from localStorage", e);
    }
  }
};

// Lifecycle hooks
onMounted(() => {
  loadScanHistory();

  // 连接MQTT
  connectMqtt(handleRfidReceived);

  // 监听MQTT状态变化
  const statusInterval = setInterval(() => {
    updateDeviceStatus();
  }, 1000);

  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(statusInterval);
    disconnectMqtt();
  });
});
</script>

<style scoped>
.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.scan-card,
.result-card,
.help-card {
  height: 100%;
  margin-bottom: 24px;
}

.scanner-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.scanner-animation {
  width: 250px;
  height: 150px;
  background-color: #f0f0f0;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #d9d9d9;
}

.scanner-animation::before {
  content: "RFID";
  font-size: 32px;
  font-weight: bold;
  color: #cccccc;
}

.scanner-light {
  position: absolute;
  width: 100%;
  height: 10px;
  background: linear-gradient(
    to bottom,
    rgba(24, 144, 255, 0),
    rgba(24, 144, 255, 0.5),
    rgba(24, 144, 255, 0)
  );
  top: 0;
  transform: translateY(-10px);
}

.scanning .scanner-light {
  animation: scan 1.5s linear infinite;
}

@keyframes scan {
  0% {
    transform: translateY(-10px);
  }
  100% {
    transform: translateY(150px);
  }
}

.scanner-status {
  margin-bottom: 20px;
  text-align: center;
}

.scanner-controls {
  width: 100%;
  max-width: 400px;
}

.helper-text {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.medicine-info {
  margin-top: 16px;
}

.medicine-info h3 {
  margin-bottom: 16px;
}

.scan-result-success,
.scan-result-error {
  padding: 16px 0;
}

.result-actions {
  display: flex;
  gap: 16px;
}

.scan-history-item {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  align-items: center;
}

.scan-history-item span:last-child {
  font-size: 12px;
  color: #999;
}

.scan-result-tags {
  display: flex;
  gap: 8px;
}

.help-content {
  padding: 16px 0;
}

.error-message {
  margin-top: 8px;
  width: 100%;
}

.debug-info {
  width: 100%;
  margin-top: 16px;
  margin-bottom: 16px;
}

.connection-options {
  margin-top: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
